package com.atguigu.gmallre.mock.stage;


import com.atguigu.mock.util.LogUtil;
import com.atguigu.mock.util.RandomBox;
import com.atguigu.gmallre.mock.bean.*;

import com.atguigu.gmallre.mock.config.AppConfig;
import com.atguigu.gmallre.mock.constant.GmallConstant;
import com.atguigu.gmallre.mock.factory.UserSession;
import com.atguigu.gmallre.mock.log.*;

import com.atguigu.gmallre.mock.log.enums.ActionId;
import com.atguigu.gmallre.mock.log.enums.ItemType;
import com.atguigu.gmallre.mock.log.enums.PageId;
import com.atguigu.gmallre.mock.service.*;

import com.atguigu.mock.util.RandomNum;
import com.atguigu.mock.util.RandomNumString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("order")
@Slf4j
public class OrderStage implements Stage {

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    BaseProvinceService baseProvinceService;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    CartInfoService cartInfoService;

    @Autowired
    CouponInfoService couponInfoService;
    @Autowired
    CouponUseService couponUseService;

    @Autowired
    OrderDetailCouponService orderDetailCouponService;


    @Autowired
    OrderStatusLogService orderStatusLogService;

    @Autowired
    ActivityOrderService activityOrderService;

    @Autowired
    LogService logService;

    @Autowired
    LoginStage loginStage;

    @Override
    public boolean handle() {


        if ((UserSession.getLastPageId() == PageId.good_detail && UserSession.getBuyingSkuInfo() != null)
                || (UserSession.getCartList() != null && UserSession.getCartList().size() > 0)) {

            //生成订单
            OrderInfo orderInfo = genOrder();

            //日志部分
            AppMain appMain = mainlog(orderInfo);
            loginStage.checkLogin(appMain);


            logService.doLog(appMain) ;
            UserSession.setOrderInfo(orderInfo);
            UserSession.setLastPageId(PageId.trade);
            return true;
        } else {
            log.debug("该用户:{}没有可下单的商品!" , UserSession.getUserInfo().getId() );
            return false;
        }
    }


    private AppMain mainlog(OrderInfo orderInfo) {
        AppCommon appCommon = UserSession.getAppCommon();

        Long orderId = orderInfo.getId();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        List<Long> skuIdList = orderDetailList.stream().map(orderDetail -> orderDetail.getSkuId()).collect(Collectors.toList());
        String skuIds = StringUtils.join(skuIdList, ",");


        Integer durTime = RandomNum.getRandInt(5000, AppConfig.page_during_max_ms);



        AppPage appPage = AppPage.builder()
                .last_page_id(UserSession.getLastPageId())
                .item(skuIds)
                .item_type(ItemType.sku_ids)
                .during_time(durTime)
                .page_id(PageId.trade).buildFinal();


        UserSession.addTimeByDuringTime(appPage.getDuring_time());

        AppMain appMain = AppMain.builder().common(appCommon).page(appPage) .ts(UserSession.getCurDateTime().getTime()).checkError().build();

        if(orderInfo.getCouponUse()!=null){
            AppAction couponAction = new AppAction(ActionId.get_coupon, ItemType.coupon_id, orderInfo.getCouponUse().getCouponId().toString());
            appMain.addAction(couponAction);

        }

        return appMain;

    }


    private OrderInfo genOrder() {

        List<CartInfo> cartList = UserSession.getCartList();

        List<OrderDetail> orderDetailList = new ArrayList<>();


        //判断直接购买还是从购物车结算
        if (UserSession.getLastPageId() == PageId.good_detail && UserSession.getBuyingSkuInfo() != null) {
            SkuInfo skuInfo = UserSession.getBuyingSkuInfo();
            orderDetailList.add(genOrderDetailFromSku(skuInfo));
        } else if (UserSession.getLastPageId() == PageId.cart && cartList.size() > 0) {
            for (CartInfo cartInfo : cartList) {
                boolean ifCart = RandomBox.builder().add(true, AppConfig.if_order_rate).add(false, 100 - AppConfig.if_order_rate).build().getRandBoolValue();
                if(!ifCart&& cartInfo.getIsOrdered()==1){
                    continue;
                }

                orderDetailList.add(genOrderDetailFromCart(cartInfo));
                cartInfo.setIsOrdered(1);
                cartInfo.setOrderTime(UserSession.getCurDateTime());
            }
            cartInfoService.saveOrUpdateBatch(cartList, 100);
        }

        OrderInfo orderInfo = genOrderInfo(orderDetailList);

        takeCoupon(orderInfo); //尝试领取购物券
        joinActivity(orderInfo);//尝试参加活动
        orderInfoService.saveOrUpdate(orderInfo);
        orderStatusLogService.genOrderStatusLog(orderInfo);
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(orderInfo.getId());
        }
        orderDetailService.saveOrUpdateBatch(orderDetailList, 10);

        usingCoupon(orderInfo.getCouponUse());//保存购物券使用
        saveOrderActivity(orderInfo.getActivityOrder());//保存活动参与
        return orderInfo;


    }


    private OrderInfo genOrderInfo(List<OrderDetail> orderDetailList) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);

        String tradeInfo = orderInfo.getOrderSubject();
        orderInfo.setConsignee(UserSession.getUserInfo().getName());
        orderInfo.setConsigneeTel(UserSession.getUserInfo().getPhoneNum());
        orderInfo.setUserId(UserSession.getUserInfo().getId());
        orderInfo.setTradeBody(tradeInfo);
        orderInfo.setCreateTime(UserSession.getCurDateTime());
        orderInfo.setRefundableTime(DateUtils.addDays(UserSession.getCurDateTime(), 7));
        orderInfo.setOrderStatus(GmallConstant.ORDER_STATUS_UNPAID);
        orderInfo.setPaymentWay(GmallConstant.PAYMENT_WAY_ONLINE);
        orderInfo.setOutTradeNo(RandomNumString.getRandNumString(1, 9, 15, ""));
        orderInfo.setProvinceId( Integer.valueOf( UserSession.getAppCommon().getAr()) );
        orderInfo.sumOrderAmount();

        return orderInfo;
    }

    private OrderDetail genOrderDetailFromCart(CartInfo cartInfo) {


        OrderDetail orderDetail = new OrderDetail();
        SkuInfo skuInfo = skuInfoService.getById(cartInfo.getSkuId(), true);
        orderDetail.setSkuInfo(skuInfo);
        orderDetail.setSkuId(cartInfo.getSkuId());
        orderDetail.setSkuName(cartInfo.getSkuName());
        orderDetail.setOrderPrice(cartInfo.getCartPrice());
        orderDetail.setSkuNum(cartInfo.getSkuNum());
        orderDetail.setSplitActivityAmount(BigDecimal.ZERO)  ;
        orderDetail.setSplitCouponAmount(BigDecimal.ZERO) ;
        orderDetail.calcTotalAmount();
           orderDetail.setCreateTime(UserSession.getCurDateTime());

        return orderDetail;
    }


    private OrderDetail genOrderDetailFromSku(SkuInfo skuInfo) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuInfo(skuInfo);
        orderDetail.setSkuId(skuInfo.getId());
        orderDetail.setSkuName(skuInfo.getSkuName());
        orderDetail.setOrderPrice(skuInfo.getPrice());
        orderDetail.setSkuNum(1L);
        orderDetail.setSplitActivityAmount(BigDecimal.ZERO)  ;
        orderDetail.setSplitCouponAmount(BigDecimal.ZERO) ;
        orderDetail.calcTotalAmount();
        orderDetail.setCreateTime(UserSession.getCurDateTime());
        return orderDetail;
    }


    public void  takeCoupon(OrderInfo orderInfo){

        CouponUse couponUse = couponInfoService.takeBestCouponForOrder(orderInfo);
        //领取购物券+ 直接使用
        if(couponUse!=null){
            CouponInfo couponInfo = couponUse.getCouponInfo();
            couponUse.setCouponStatus(GmallConstant.COUPON_STATUS_UNUSED);
            couponUse.setCreateTime(UserSession.getCurDateTime());
            couponUse.setGetTime( UserSession.getCurDateTime());
            couponUse.setUserId(UserSession.getUserInfo().getId());
            couponUse.setCouponId(couponInfo.getId());
            couponUse.setOrderInfo(orderInfo);
            couponUseService.save(couponUse);
            orderInfo.setCouponUse(couponUse);

            couponUse.splitAmount(); //把优惠金额分摊到各个订单明细
            orderInfo.sumOrderAmount();
        }
    }

    public  void   usingCoupon( CouponUse couponUse){
        if(couponUse!=null){
            couponUse.syncOrderInfo();
            couponUseService.saveOrUpdate(couponUse);
            couponUse.syncOrderDetail();
            orderDetailCouponService.saveOrUpdateBatch(couponUse.getOrderDetailCouponList());

        }
    }

    public void joinActivity(OrderInfo orderInfo){
        ActivityOrder activityOrder = activityOrderService.joinActivityForOrder(orderInfo);
        if(activityOrder!=null){
            orderInfo.setActivityOrder(activityOrder);
            activityOrder.splitAmount();
            orderInfo.sumOrderAmount();
        }
    }

    public void saveOrderActivity(ActivityOrder activityOrder){
        if(activityOrder!=null){
            activityOrder.syncOrderDetail();
            activityOrderService.saveActivityOrderList(activityOrder.getOrderDetailActivityList());

        }
    }


}
